#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <pqxx/transaction.hxx>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/light/list_pole_area";

	void light_list_pole_area(Request& req, pqxx::connection& dbconn, SessionContext& , const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& from_s = query["from"];
		auto& count_s = query["count"];
		auto& section_id = query["section_id"];
		unsigned int from = from_s.empty() ? unsigned(0): boost::lexical_cast<unsigned>(from_s);
		unsigned int limit = count_s.empty() ? unsigned(2000): boost::lexical_cast<unsigned>(count_s);
		limit = std::min(limit, unsigned(2000));
		limit = std::max(limit, unsigned(1));

		auto& west_s = query["w"];
		auto& east_s = query["e"];
		auto& south_s = query["s"];
		auto& north_s = query["n"];
		double west = boost::lexical_cast<double>(west_s);
		double east = boost::lexical_cast<double>(east_s);
		double south = boost::lexical_cast<double>(south_s);
		double north = boost::lexical_cast<double>(north_s);

		StreamGroup sg(req);
		auto& fout = sg.fout;
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

		pqxx::work w(dbconn);
#if 1
		std::string total;
		{
			std::string sql = section_id.empty() ? "list_pole_by_area" : "list_pole_by_area_section";
			TotalCount tc(w, sql + "_total");
			tc(west)(east)(south)(north);
			if (!section_id.empty())
				tc(section_id);
			total = tc.result();
		}
		fout << boost::format(R"({"func":"light/list_pole_area",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":)") % total;
#endif

		auto result = section_id.empty() 
			? (w.prepared("list_pole_by_area")(west)(east)(south)(north)(limit)(from).exec())
			: (w.prepared("list_pole_by_area_section")(west)(east)(south)(north)(section_id)(limit)(from).exec());
		fout << result2json(result, 2);

		fout << "}}";
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::light_list_pole_area);
}



